// AI医疗问答Vue组件
const AIChatComponent = {
  template: `
    <div class="ai-chat-container">
      <div class="ai-chat-header">
        <h2>医疗AI助手</h2>
        <div class="ai-status">{{ connectionStatus }}</div>
      </div>

      <div class="ai-chat-messages" ref="messageContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['ai-message', message.isUser ? 'user-message' : 'ai-response']">
          <div class="message-content">{{ message.text }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>

      <div class="ai-chat-input">
        <input 
          type="text" 
          v-model="userInput" 
          @keyup.enter="sendMessage" 
          :disabled="!isConnected"
          placeholder="请输入您的问题..."
        >
        <button @click="sendMessage" :disabled="!isConnected || userInput.trim() === ''">发送</button>
      </div>
    </div>
  `,
  
  data() {
    return {
      userInput: '',
      messages: [],
      socket: null,
      isConnected: false,
      connectionStatus: '正在连接...',
      userId: 'user' + Math.floor(Math.random() * 1000)
    };
  },
  
  mounted() {
    this.connectWebSocket();
    // 滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  },
  
  beforeDestroy() {
    // 组件销毁前关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
    }
  },
  
  methods: {
    connectWebSocket() {
      // 创建WebSocket连接
      const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const wsUrl = `${wsProtocol}//${window.location.host}/ws/ai/${this.userId}/`;
      this.socket = new WebSocket(wsUrl);
      
      // WebSocket事件处理
      this.socket.onopen = this.handleSocketOpen;
      this.socket.onmessage = this.handleSocketMessage;
      this.socket.onclose = this.handleSocketClose;
      this.socket.onerror = this.handleSocketError;
    },
    
    handleSocketOpen(event) {
      this.isConnected = true;
      this.connectionStatus = '已连接';
      console.log('WebSocket连接已建立');
    },
    
    handleSocketMessage(event) {
      try {
        const data = JSON.parse(event.data);
        
        // 处理不同类型的消息
        if (data.type === 'welcome') {
          this.addMessage(data.message, false);
        } else if (data.type === 'typing') {
          // 可以添加"正在输入"的指示器，或者忽略
        } else if (data.type === 'answer') {
          this.addMessage(data.message, false);
        } else if (data.type === 'error') {
          this.addMessage(data.message, false);
        }
      } catch (error) {
        console.error('解析WebSocket消息出错:', error);
      }
    },
    
    handleSocketClose(event) {
      this.isConnected = false;
      this.connectionStatus = '已断开连接';
      console.log('WebSocket连接已关闭:', event);
      
      // 尝试重新连接
      setTimeout(() => {
        this.connectWebSocket();
      }, 3000);
    },
    
    handleSocketError(error) {
      this.connectionStatus = '连接错误';
      console.error('WebSocket错误:', error);
    },
    
    sendMessage() {
      if (!this.isConnected || this.userInput.trim() === '') {
        return;
      }
      
      // 添加用户消息到列表
      this.addMessage(this.userInput, true);
      
      // 发送消息到WebSocket服务器
      this.socket.send(JSON.stringify({
        userid: this.userId,
        mes: this.userInput
      }));
      
      // 清空输入框
      this.userInput = '';
    },
    
    addMessage(text, isUser) {
      const now = new Date();
      const timeString = now.toLocaleTimeString();
      
      this.messages.push({
        text,
        isUser,
        time: timeString
      });
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    scrollToBottom() {
      if (this.$refs.messageContainer) {
        this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight;
      }
    }
  }
};

// 导出组件
if (typeof module !== 'undefined' && module.exports) {
  module.exports = AIChatComponent;
} 